package com.stn.zjx.givingtreasure.activity.set;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.google.gson.Gson;
import com.jungly.gridpasswordview.GridPasswordView;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.userlogin.UserPassResetActivity;
import com.stn.zjx.givingtreasure.activity.userwallet.UserTransferActivity;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.domain.StatusDomain;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.event.UserResetPassEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.PayNetImpl;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.table.User;
import com.stn.zjx.givingtreasure.utils.SoftInputUtils;
import com.stn.zjx.givingtreasure.widget.VirtualKeyboardView;
import com.vondear.rxtools.RxActivityTool;
import com.vondear.rxtools.RxKeyboardTool;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.shaohui.bottomdialog.BaseBottomDialog;
import me.shaohui.bottomdialog.BottomDialog;

public class PasswordSetActivity extends BaseActivity {

    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.sure_bt)
    TextView sureBt;
    @BindView(R.id.go_login_password)
    RelativeLayout goLoginPassword;
    @BindView(R.id.go_pay_password)
    RelativeLayout goPayPassword;

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Override
    public void initComponent() {
        actionTitle.setText(getString(R.string.password_set));
       // initPayDialog();
    }


    public void initPayDialog() {
        Dialog pay_dialog;
        GridPasswordView gridPasswordView;
        VirtualKeyboardView virtualKeyboardView;
        GridView gridView;
        LinearLayout under;
        pay_dialog = new Dialog(PasswordSetActivity.this,R.style.dialog_soft_input);
        pay_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        pay_dialog.setContentView(R.layout.dialog_input_pay_password);
        WindowManager.LayoutParams lp = pay_dialog.getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        pay_dialog.getWindow().setAttributes(lp);
        pay_dialog.getWindow().setWindowAnimations(R.style.myDialogStyle);
        View close = pay_dialog.findViewById(R.id.close);
        TextView forgetpassword_bt = pay_dialog.findViewById(R.id.forgetpassword_bt);
        gridPasswordView = pay_dialog.findViewById(R.id.grid_password_edit);
        gridPasswordView.mInputView.setFocusable(false);
        gridPasswordView.mInputView.setFocusableInTouchMode(false);
        virtualKeyboardView = pay_dialog.findViewById(R.id.virtualKeyboardView);
        gridView=pay_dialog.findViewById(R.id.gv_keybord);
        gridPasswordView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        pay_dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
//                // 获取焦点
//                gridPasswordView.requestFocus();
//                SoftInputUtils.openSoftInput(UserTransferActivity.this, pay_dialog.getCurrentFocus());
            }
        });
        pay_dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                gridPasswordView.clearPassword();
//                gridPasswordView.requestFocus();
//                SoftInputUtils.closedSoftInput(UserTransferActivity.this);
            }
        });


        forgetpassword_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                User user = UserService.getInstance(getApplicationContext())
                        .getOnlineLoginUser();
                if (user == null) {
                    return;
                }
                if (TextUtils.isEmpty(user.getUserPhone())) {
                    RxActivityTool.skipActivity(getApplicationContext(), UserPhoneBindActivity.class);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("phone", user.getUserPhone());
                    RxActivityTool.skipActivity(getApplicationContext(), ForgetPayPassActivity.class, bundle);
                }

            }
        });
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                pay_dialog.dismiss();
            }
        });


        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                if (position < 11 && position != 9) {    //点击0~9按钮
                    if(gridPasswordView.getPassWord().length()<6){
                        gridPasswordView.setPassword(gridPasswordView.getPassWord()+virtualKeyboardView.getValueList().get(position).get("name"));
                    }
                    if(gridPasswordView.getPassWord().length()==6){
                        User onlineUser = UserService.getInstance(PasswordSetActivity.this).getOnlineLoginUser();
                        if (onlineUser == null) {
                            return;
                        }
                        check_paypass( gridPasswordView.getPassWord(),pay_dialog);

                    }
                } else {
                    if (position == 11) {      //点击退格键
                        if(gridPasswordView.getPassWord().length()>0){
                            gridPasswordView.setPassword(gridPasswordView.getPassWord().substring(0,gridPasswordView.getPassWord().length()-1));
                        }
                    }
                }
            }
        });

        pay_dialog.show();
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_set_password);
        ButterKnife.bind(this);
        initComponent();
    }


    @Override
    public boolean isSupportSwipeBack() {
        return true;
    }

    @Override
    protected void onStart() {
        super.onStart();

    }


    @OnClick({R.id.back_bt,R.id.go_login_password,R.id.go_pay_password})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;
            case R.id.go_login_password:
                RxActivityTool.skipActivity(this, UserPassResetActivity.class);
                break;
            case R.id.go_pay_password:
                isCheckJoinPassword();
                break;
         }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void UserResetPassEvent(UserResetPassEvent event) {
        finish();
    }


    public void isCheckJoinPassword(){
         if(UserService.getInstance(this).getOnlineLoginUser()==null){
             return;
         }
        PayNetImpl
                .join_set_user_paypassword(UserService.getInstance(this).getOnlineLoginUser().getToken(),
                        "join_set_user_paypassword", new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                                showLoading();
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                dissmissLoading();
                            }
                            @Override
                            public void onSuccess(Response<String> response) {
                                StatusDomain domain=new Gson().fromJson(response.body(),StatusDomain.class);
                                 switch (domain.getStatus()){
                                     case BaseApi.REQUEST_SUCCESS_CODE:
                                         RxActivityTool.skipActivity(getApplicationContext(), PayPasswordSetActivity.class);
                                         break;
                                     case BaseApi.REQUEST_ChECK_PAY_PASSWORD_CODE:
                                            initPayDialog();
                                         break;
                                     default:
                                        showToast(domain.getMessage());
                                         break;
                                 }

                            }
                        });

    }

    public void  check_paypass(String password,Dialog pay_dialog){
        showToast(password);
        PayNetImpl
                .check_user_paypassword(UserService.getInstance(this).getOnlineLoginUser().getToken(),
                        password,
                        "check_user_paypassword", new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                              showLoading();
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                             dissmissLoading();
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                StatusDomain domain=new Gson().fromJson(response.body(),StatusDomain.class);
                                switch (domain.getStatus()){
                                    case BaseApi.REQUEST_SUCCESS_CODE:
                                       RxActivityTool.skipActivity(getApplicationContext(),PayPasswordSetActivity.class);
                                        break;
                                    default:
                                        showToast(domain.getMessage());
                                        break;
                                }
                                pay_dialog.dismiss();
                            }
                        });
    }


    public void addLayoutListener(final View main, final View scroll) {
        main.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                //1、获取main在窗体的可视区域
                main.getWindowVisibleDisplayFrame(rect);
                //2、获取main在窗体的不可视区域高度，在键盘没有弹起时，main.getRootView().getHeight()调节度应该和rect.bottom高度一样
                int mainInvisibleHeight = main.getRootView().getHeight() - rect.bottom;
                int screenHeight = main.getRootView().getHeight();//屏幕高度
                //3、不可见区域大于屏幕本身高度的1/4：说明键盘弹起了
                if (mainInvisibleHeight > screenHeight / 4) {
                    int[] location = new int[2];
                    scroll.getLocationInWindow(location);
                    // 4､获取Scroll的窗体坐标，算出main需要滚动的高度
                    int srollHeight = (location[1] + scroll.getHeight()) - rect.bottom;
                    //5､让界面整体上移键盘的高度
                    main.scrollTo(0, srollHeight);
                } else {
                    //3、不可见区域小于屏幕高度1/4时,说明键盘隐藏了，把界面下移，移回到原有高度
                    main.scrollTo(0, 0);
                }
            }
        });
    }



}
